package com.example.kemgdemo.excepiton;

import com.example.kemgdemo.model.Result;
import com.example.kemgdemo.util.ResultUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 学号：1401030048
 * Created by 梁嘉伟 on 2019/7/11
 */
@ControllerAdvice
public class ExceptionHandle {
    //记录异常
    private final static Logger logger = LoggerFactory.getLogger(ExceptionHandle.class);

    @ExceptionHandler(value = Exception.class)              //全局捕获异常--@ExceptionHandler
    @ResponseBody                                           //表示该方法的返回结果直接写入 HTTP response body 中
    public Result handle(Exception e){

        if (e instanceof BaseException){
            BaseException baseException = (BaseException)e;
            return ResultUtil.error(baseException.getCode(),
                    baseException.getMessage());
        }
        else {
            logger.error("系统异常 {}", e);
            return ResultUtil.error(-1, e.getMessage());
        }
    }
}
